package com.example.news

import android.app.ProgressDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.adapter.NewsAdapter
import com.example.news.databinding.ActivityNewsBinding
import com.example.news.entity.Record
import com.example.news.intent.NewsIntent
import com.example.news.viewmodel.NewsState
import com.example.news.viewmodel.NewsViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/news/NewsActivity")
class NewsActivity : AppCompatActivity() {
    lateinit var vm:NewsViewModel
    lateinit var dialog:ProgressDialog
    lateinit var rv:RecyclerView
    lateinit var db:ActivityNewsBinding
    lateinit var newsAdapter: NewsAdapter
    var list= mutableListOf<Record>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        db= ActivityNewsBinding.inflate(layoutInflater)
        setContentView(db.root)
        vm=ViewModelProvider(this).get(NewsViewModel::class.java)

        newsAdapter= NewsAdapter(this,list,object :NewsAdapter.ItemClickListener{
            override fun onItemClick(position: Int, entity: Record) {
                Toast.makeText(this@NewsActivity, entity.title, Toast.LENGTH_SHORT).show()
            }
        },object :NewsAdapter.ItemLongClickListener{
            override fun onItemLongClick(entity: Record) {
                Toast.makeText(this@NewsActivity, entity.content, Toast.LENGTH_SHORT).show()
            }

        })

        db.rv.apply {
            adapter=newsAdapter
            layoutManager=LinearLayoutManager(this@NewsActivity)
        }


        lifecycleScope.launch {
            //接收到状态改变
            vm.newsState.collect{
                when(it){
                    is NewsState.Loading->{
                        dialog= ProgressDialog(this@NewsActivity)
                        dialog.setTitle("加载中……")
                        dialog.create()
                        dialog.show()
                    }
                    is NewsState.Success->{//成功
                        dialog.dismiss()
                        Log.i("===",it.list.toString())
                        list.addAll(it.list)
                        newsAdapter.notifyDataSetChanged()
                    }
                    is NewsState.Error->{
                        dialog.dismiss()
                        Toast.makeText(this@NewsActivity, it.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }


        lifecycleScope.launch {
            //发起要操作的意图
            vm.newsChannel.send(NewsIntent.getNewsList(1,0))
        }
    }
}